package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"strings"
	"time"
	models2 "tuowei.com/app/admin/models"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
)

type ApiIndex struct {
	api.Api
}

func (e ApiIndex) Config(c *gin.Context) {
	s := service.ApiIndex{}
	req := dto.ConfigReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	lists := make([]models.SysSubject, 0)
	db := e.Orm.Debug().Select("id", "name").Where("deleted_at is null")
	if req.Province != "" {
		db.Where("province = ?", req.Province)
	}
	err = db.Find(&lists).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	lista := make([]models.SysAppConfig, 0)
	err = e.Orm.Debug().Where("deleted_at is null and is_show = '1'").Order("sort").Find(&lista).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	listc := make([]models.SysIndexCategoryConfig, 0)
	err = e.Orm.Debug().Where("deleted_at is null and is_show = '1'").Order("sort").Find(&listc).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	type IndexCategory struct {
		IndexCategoryConfig interface{} `json:"index_category_config"`
		ConfigList          interface{} `json:"config_list"`
	}
	type ByCourse struct {
		Subject string `json:"subject"`
		//SubjectCode string      `json:"subject_code"`
		Course []IndexCategory `json:"course"`
	}

	indexCategoryList := make([]ByCourse, 0)
	//todo NameCode要暴露出来，提供给后台配置
	/*
		jptj:精品推荐
		mskc:面授课程
		xskc:线上课程
		zbkc:直播课程
		xxzl:学习资料
	*/
	//首页加精选=全部课程部分课目
	byCourse := ByCourse{}
	byCourse.Subject = "精选"
	for _, c := range listc {
		switch c.NameCode {
		case "jptj": //精品推荐
			indexCategory := IndexCategory{
				IndexCategoryConfig: c,
			}

			listb := make([]models.SysCourseByBoutique, 0)
			db = e.Orm.Debug().Where("deleted_at is null and is_boutique = '1'")
			if req.Province != "" {
				db.Where("province = ?", req.Province)
			}
			err = db.Limit(c.PageLimit).Find(&listb).Error
			if err != nil {
				e.Logger.Errorf("db error: %s", err)
				return
			}
			indexCategory.ConfigList = listb
			byCourse.Course = append(byCourse.Course, indexCategory)

		case "mskc": //面授课程
			indexCategory := IndexCategory{
				IndexCategoryConfig: c,
			}

			listo := make([]models.SysOfflineCourse, 0)
			db = e.Orm.Debug().Where("deleted_at is null and status = '1'")
			if req.Province != "" {
				db.Where("province = ?", req.Province)
			}
			err = db.Limit(c.PageLimit).Find(&listo).Error
			if err != nil {
				e.Logger.Errorf("db error: %s", err)
				return
			}

			indexCategory.ConfigList = listo

			byCourse.Course = append(byCourse.Course, indexCategory)
		case "xskc": //线上课程
			indexCategory := IndexCategory{
				IndexCategoryConfig: c,
			}

			listo := make([]models.SysCourse, 0)
			db = e.Orm.Debug().Where("deleted_at is null and status = '1' and course_type = 'online'")
			if req.Province != "" {
				db.Where("province = ?", req.Province)
			}
			err = db.Limit(c.PageLimit).Find(&listo).Error
			if err != nil {
				e.Logger.Errorf("db error: %s", err)
				return
			}

			indexCategory.ConfigList = listo

			byCourse.Course = append(byCourse.Course, indexCategory)
		case "zbkc": //直播课程
			indexCategory := IndexCategory{
				IndexCategoryConfig: c,
			}
			listoCopy := make([]models.SysCourseCopy, 0)
			listo := make([]models.SysCourse, 0)
			db = e.Orm.Debug().Where("deleted_at is null and status = '1' and course_type = 'live'")
			if req.Province != "" {
				db.Where("province = ?", req.Province)
			}
			err = db.Limit(c.PageLimit).Find(&listo).Error
			if err != nil {
				e.Logger.Errorf("db error: %s", err)
				return
			}
			for _, o := range listo {
				listl := models.SysLecturer{}
				err = e.Orm.Debug().Where("id = ?", o.LecturerId).First(&listl).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					continue
				}
				cc := models.SysCourseCopy{}
				//教师信息
				cc.LecturerName = listl.Name
				cc.LecturerAvatar = listl.Avatar

				cc.Name = o.Name
				cc.Subject = o.Subject
				cc.Status = o.Status
				cc.CourseId = o.CourseId
				cc.Cover = o.Cover
				cc.Price = o.Price
				cc.LecturerId = o.LecturerId
				cc.CourseType = o.CourseType
				cc.CreatedAt = o.CreatedAt
				cc.Introduction = o.Introduction
				cc.PublicRange = o.PublicRange
				cc.Creator = o.Creator
				cc.Province = o.Province
				cc.AuditionCourseName = o.AuditionCourseName
				cc.AuditionLink = o.AuditionLink
				cc.Contacts = o.Contacts
				cc.CourseWareJson = o.CourseWareJson

				cc.IsBindOffline = o.IsBindOffline
				cc.IsBoutique = o.IsBoutique
				cc.LiveUrl = o.LiveUrl
				cc.OnlineClass = o.OnlineClass
				cc.OnlineClassId = o.OnlineClassId
				cc.Outline = o.Outline
				cc.Sales = o.Sales
				cc.SerialNum = o.SerialNum
				cc.Telephone = o.Telephone
				cc.TermOfValidity = o.TermOfValidity
				cc.LiveStatus = "1"
				if o.StartTime.IsZero() {
					cc.StartTime = ""
				} else {
					cc.StartTime = o.StartTime.Format("2006-01-02 15:04:05")
					if o.StartTime.Unix() > time.Now().Unix() {
						//未开始
					} else {
						cc.LiveStatus = "2"
						if o.EndTime.IsZero() {
							cc.EndTime = ""
						} else {
							cc.EndTime = o.EndTime.Format("2006-01-02 15:04:05")
							if o.EndTime.Unix() < time.Now().Unix() {
								cc.LiveStatus = "3"
							}
						}
					}
				}
				listoCopy = append(listoCopy, cc)

			}

			indexCategory.ConfigList = listoCopy
			byCourse.Course = append(byCourse.Course, indexCategory)
		case "xxzl": //学习资料
			indexCategory := IndexCategory{
				IndexCategoryConfig: c,
			}

			listo := make([]models.SysMaterial, 0)
			db = e.Orm.Debug().Where("deleted_at is null and status = '1'")
			if req.Province != "" {
				db.Where("province = ?", req.Province)
			}
			err = db.Limit(c.PageLimit).Find(&listo).Error
			if err != nil {
				e.Logger.Errorf("db error: %s", err)
				return
			}

			indexCategory.ConfigList = listo

			byCourse.Course = append(byCourse.Course, indexCategory)
		}

	}

	indexCategoryList = append(indexCategoryList, byCourse)
	for _, s := range lists {
		byCourse := ByCourse{}
		byCourse.Subject = s.Name
		for _, c := range listc {
			switch c.NameCode {
			case "jptj": //精品推荐
				indexCategory := IndexCategory{
					IndexCategoryConfig: c,
				}

				listb := make([]models.SysCourseByBoutique, 0)
				db = e.Orm.Debug().Where("deleted_at is null and is_boutique = '1' and subject = ?", s.Name)
				if req.Province != "" {
					db.Where("province = ?", req.Province)
				}
				err = db.Limit(c.PageLimit).Find(&listb).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					return
				}
				indexCategory.ConfigList = listb
				byCourse.Course = append(byCourse.Course, indexCategory)

			case "mskc": //面授课程
				indexCategory := IndexCategory{
					IndexCategoryConfig: c,
				}

				listo := make([]models.SysOfflineCourse, 0)
				db = e.Orm.Debug().Where("deleted_at is null and status = '1' and subject = ?", s.Name)
				if req.Province != "" {
					db.Where("province = ?", req.Province)
				}
				err = db.Limit(c.PageLimit).Find(&listo).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					return
				}

				indexCategory.ConfigList = listo

				byCourse.Course = append(byCourse.Course, indexCategory)
			case "xskc": //线上课程
				indexCategory := IndexCategory{
					IndexCategoryConfig: c,
				}

				listo := make([]models.SysCourse, 0)
				db = e.Orm.Debug().Where("deleted_at is null and status = '1' and course_type = 'online' and subject = ?", s.Name)
				if req.Province != "" {
					db.Where("province = ?", req.Province)
				}
				err = db.Limit(c.PageLimit).Find(&listo).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					return
				}

				indexCategory.ConfigList = listo

				byCourse.Course = append(byCourse.Course, indexCategory)
			case "zbkc": //直播课程
				indexCategory := IndexCategory{
					IndexCategoryConfig: c,
				}
				listoCopy := make([]models.SysCourseCopy, 0)
				listo := make([]models.SysCourse, 0)
				db = e.Orm.Debug().Where("deleted_at is null and status = '1' and course_type = 'live' and subject = ?", s.Name)
				if req.Province != "" {
					db.Where("province = ?", req.Province)
				}
				err = db.Limit(c.PageLimit).Find(&listo).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					return
				}
				for _, o := range listo {
					listl := models.SysLecturer{}
					err = e.Orm.Debug().Where("id = ?", o.LecturerId).First(&listl).Error
					if err != nil {
						e.Logger.Errorf("db error: %s", err)
						continue
					}
					cc := models.SysCourseCopy{}
					//教师信息
					cc.LecturerName = listl.Name
					cc.LecturerAvatar = listl.Avatar
					//
					cc.Name = o.Name
					cc.Subject = o.Subject
					cc.Status = o.Status
					cc.CourseId = o.CourseId
					cc.Cover = o.Cover
					cc.Price = o.Price
					cc.LecturerId = o.LecturerId
					cc.CourseType = o.CourseType
					cc.CreatedAt = o.CreatedAt
					cc.Introduction = o.Introduction
					cc.PublicRange = o.PublicRange
					cc.Creator = o.Creator
					cc.Province = o.Province
					cc.AuditionCourseName = o.AuditionCourseName
					cc.AuditionLink = o.AuditionLink
					cc.Contacts = o.Contacts
					cc.CourseWareJson = o.CourseWareJson

					cc.IsBindOffline = o.IsBindOffline
					cc.IsBoutique = o.IsBoutique
					cc.LiveUrl = o.LiveUrl
					cc.OnlineClass = o.OnlineClass
					cc.OnlineClassId = o.OnlineClassId
					cc.Outline = o.Outline
					cc.Sales = o.Sales
					cc.SerialNum = o.SerialNum
					cc.Telephone = o.Telephone
					cc.TermOfValidity = o.TermOfValidity
					cc.LiveStatus = "1"
					if o.StartTime.IsZero() {
						cc.StartTime = ""
					} else {
						cc.StartTime = o.StartTime.Format("2006-01-02 15:04:05")
						if o.StartTime.Unix() > time.Now().Unix() {
							//未开始
						} else {
							cc.LiveStatus = "2"
							if o.EndTime.IsZero() {
								cc.EndTime = ""
							} else {
								cc.EndTime = o.EndTime.Format("2006-01-02 15:04:05")
								if o.EndTime.Unix() < time.Now().Unix() {
									cc.LiveStatus = "3"
								}
							}
						}
					}

					listoCopy = append(listoCopy, cc)

				}

				indexCategory.ConfigList = listoCopy
				byCourse.Course = append(byCourse.Course, indexCategory)
			case "xxzl": //学习资料
				indexCategory := IndexCategory{
					IndexCategoryConfig: c,
				}

				listo := make([]models.SysMaterial, 0)
				db = e.Orm.Debug().Where("deleted_at is null and status = '1' and subject = ?", s.Name)
				if req.Province != "" {
					db.Where("province = ?", req.Province)
				}
				err = db.Limit(c.PageLimit).Find(&listo).Error
				if err != nil {
					e.Logger.Errorf("db error: %s", err)
					return
				}

				indexCategory.ConfigList = listo

				byCourse.Course = append(byCourse.Course, indexCategory)
			}

		}

		indexCategoryList = append(indexCategoryList, byCourse)
	}

	type ConfigResp struct {
		SysSubject             interface{} `json:"sys_subject"`
		SysAppConfig           interface{} `json:"sys_app_config"`
		SysIndexCategoryConfig []ByCourse  `json:"sys_index_category_config"`
	}
	resp := ConfigResp{
		SysSubject:             lists,
		SysAppConfig:           lista,
		SysIndexCategoryConfig: indexCategoryList,
	}
	e.OK(resp, "查询成功")
}

func (e ApiIndex) GetLbt(c *gin.Context) {
	s := service.ApiIndex{}
	req := dto.SysLbtReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.Province = strings.Replace(req.Province, "市", "", -1)
	list := make([]models.SysConsultLBT, 0)
	db := e.Orm.Debug().Select("consult_lbt_id", "consult_lbt_name", "lbt_url", "lbt_skip_url", "lbt_skip_url_type", "province").Where("deleted_at is null and lbt_status = '1' and lbt_type = '" + req.LbtType + "'")
	if req.Province != "" {
		db.Where("province like '%" + req.Province + "%'")
	}
	err = db.Find(&list).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	e.OK(list, "查询成功")
}

func (e ApiIndex) GetWzList(c *gin.Context) {
	req := dto.ApiConsultWZGetPageReq{}
	s := service.ApiIndex{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	e.Logger.Infof("ApiConsultWZGetPageReq:%+v", req)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	list1 := make([]models.SysConsultWZ, 0)
	var count1 int64
	req.WZTop = "1"
	err = s.GetPageWZ(&req, p, &list1, &count1)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	list2 := make([]models.SysConsultWZ, 0)
	var count2 int64
	req.WZTop = "2"
	err = s.GetPageWZ(&req, p, &list2, &count2)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	for _, l := range list2 {
		list1 = append(list1, l)
	}
	e.PageOK(list1, int(count1+count2), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}
func (e ApiIndex) GetWz(c *gin.Context) {
	req := dto.ApiConsultWZGetReq{}
	s := service.ApiIndex{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.Logger.Infof("ApiConsultWZGetPageReq:%+v", req)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	object := models.SysConsultWZ{}
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}

	e.OK(object, "查询成功")
}

func (e ApiIndex) GetBoutiqueCourse(c *gin.Context) {
	req := dto.ApiCourseBoutiqueGetPageReq{}
	s := service.ApiIndex{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//上架状态
	req.Status = 1
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	list := make([]models.SysCourseByBoutique, 0)
	var count int64

	err = s.GetPageBoutiqueCourse(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")

}

func (e ApiIndex) WzAddNum(c *gin.Context) {
	s := service.ApiIndex{}
	req := dto.SysConsultWZUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.WzAddNum(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

func (e ApiIndex) Search(c *gin.Context) {
	s := service.ApiIndex{}
	req := dto.ApiIndexSearchReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	province1 := strings.Replace(req.Province, "市", "", -1)
	province := "%" + province1 + "%"
	name := "%" + req.Name + "%"
	listc := make([]models.SysCourse, 0)
	db := e.Orm.Debug().Where("status = 1 and name like ?", name)
	if req.Province != "" {
		db.Where("province like ?", province)
	}
	err = db.Limit(20).Find(&listc).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	listm := make([]models.SysMaterial, 0)
	db = e.Orm.Debug().Where("status = 1 and name like ?", name)
	if req.Province != "" {
		db.Where("province like ?", province)
	}
	err = db.Limit(20).Find(&listm).Error
	if err != nil {
		e.Logger.Errorf("db error: %s", err)
		return
	}
	// 下面的注释是去调搜也搜索的线下课程
	//listo := make([]models.SysOfflineCourse, 0)
	//db = e.Orm.Debug().Where("status = 1 and name like ?", name)
	//if req.Province != "" {
	//	db.Where("province like ?", province)
	//}
	//err = db.Limit(20).Find(&listo).Error
	//if err != nil {
	//	e.Logger.Errorf("db error: %s", err)
	//	return
	//}
	RespTabList := make([]RespTab, 0)
	tc := RespTab{}
	tc.Name = "在线课程"
	tc.Key = "list_sys_course"
	tc.List = listc
	RespTabList = append(RespTabList, tc)
	//to := RespTab{}
	//to.Name = "面授课程"
	//to.Key = "sys_offline_course"
	//to.List = listo
	//RespTabList = append(RespTabList, to)
	tm := RespTab{}
	tm.Name = "资料"
	tm.Key = "list_sys_material"
	tm.List = listm
	RespTabList = append(RespTabList, tm)

	e.OK(RespTabList, "查询成功")
}

func (e ApiIndex) GetAcademyList(c *gin.Context) {
	req := dto.ApiAcademyGetPageReq{}
	s := service.ApiIndex{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	list1 := make([]models.SysAcademy, 0)
	var count1 int64
	req.WZTop = "1"
	err = s.GetPageAcademy(&req, p, &list1, &count1)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	list2 := make([]models.SysAcademy, 0)
	var count2 int64
	req.WZTop = "2"
	err = s.GetPageAcademy(&req, p, &list2, &count2)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	for _, l := range list2 {
		list1 = append(list1, l)
	}
	e.PageOK(list1, int(count1+count2), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e ApiIndex) GetAcademy(c *gin.Context) {
	req := dto.ApiAcademyGetReq{}
	s := service.ApiIndex{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.Logger.Infof("ApiConsultWZGetPageReq:%+v", req)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	object := models.SysAcademy{}
	err = s.GetAcademy(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}

	e.OK(object, "查询成功")
}

type RespTab struct {
	Name string      `json:"name"`
	Key  string      `json:"key"`
	List interface{} `json:"list"`
}

type VersionRequest struct {
	Platform string `json:"platform" form:"platform" binding:"required"`
}

func (e ApiIndex) Version(ctx *gin.Context) {
	req := new(VersionRequest)
	err := e.MakeContext(ctx).
		MakeOrm().
		Bind(req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		Errors
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	version := new(models2.SysVersion)
	err = e.Orm.Model(models2.SysVersion{}).Where("platform = ?", req.Platform).Find(version).Error
	if err != nil {
		e.OK(nil, "success")
		return
	}
	e.OK(version, "success")
}
